package org.jeecg.modules.quartz.job;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.ObjectValueUtils;
import org.jeecg.common.util.oConvertUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.api.client.util.Maps;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollUtil;
import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.BasMaterialTemp;
import io.finer.erp.jeecg.bas.entity.ZrkPiecerate;
import io.finer.erp.jeecg.bas.entity.ZrkQzOrder;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IBasMaterialTempService;
import io.finer.erp.jeecg.bas.service.IZrkMesFqParamService;
import io.finer.erp.jeecg.bas.service.IZrkPiecerateService;
import io.finer.erp.jeecg.bas.service.IZrkQzOrderService;
import io.finer.erp.jeecg.bas.service.IZzDeviceTypeService;
import io.finer.erp.jeecg.bas.vo.ZrkMesFqParamVO;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;
import io.finer.erp.jeecg.stock.mapper.StkIoBillEntryMapper;
import io.finer.erp.jeecg.stock.service.IStkIoBillEntryService;
import io.finer.erp.jeecg.stock.service.IStkIoBillService;
import io.finer.erp.jeecg.stock.service.IStkIoMaterialLogService;
/**后期若有改动，将此文档跟新
 * 分切工资计算方式
一、13、14号机（1人干）
刀数（按500米计算/刀）*4.2元+调刀数*0.7元/刀
二、15、17、18号机（2人干，若一人干刀数*2）
刀数（按1000米计算/刀）*5.3元+调刀数*3元+平方数*0.0008元
三、19号机（1人干）
刀数（按1000米计算）*9元+平方数*0.0008元
四、12、16号机按刀数计算。（2人干、若1人干刀数*2）
刀数（不分米数）*4.5元+调刀数*2.5元+平方数*0.0008元
备注：缠卷计算方式同上（尺寸包括107、117、108、118的任何材料），但无调刀数。
     分卷筒--强粘QA、轮胎胶TE、间隔胶TE、布 6.5元一刀（不分米数）BOPP 5.5元1刀（不分米数）。
1、轮胎胶TE胶水包括：fullname中含有"/TE/"的所有物料。。
2、涂层布:涂层布/ZA/140克白底-启元、涂层布/ZA/80克白格拉辛-启元
   缎带布:缎带布/ZA/140克黄底-启元、缎带布/ZA/100克白格拉辛-启元、缎带布/ZA/100克白格拉辛-Y、缎带布/ZA/140克全木浆白硅
3、强粘QA胶水：fullname中含有"/QA/"的所有物料。
	BOPP：fullname中含有"BOPP"的所有物料


 * @ClassName PiecerateJob
 * @Description 
 * @author xzs
 * @Date 2021-08-26 14:41:30
 * @version 1.0.0
 */
public class PiecerateJob implements Job {
	@Autowired
	private IZrkPiecerateService piecerateService;
	@Autowired
	private IZrkQzOrderService qzOrderService;
	@Autowired
	private IZzDeviceTypeService deviceTypeService;
	@Autowired
	private IStkIoMaterialLogService ioMaterialLogService;
	@Autowired
	private IBasMaterialTempService basMaterialTempService;
	@Autowired
	private IStkIoBillService stkIoBillService;
	@Autowired
	private IStkIoBillEntryService stkIoBillEntryService;
	@Autowired
	private IBasMaterialService basMaterialService;
	@Autowired
	private IBasMaterialCategoryService categoryService;
	@Autowired
	private IZrkMesFqParamService zrkMesFqParamService;
	@Autowired
	private StkIoBillEntryMapper ioBillEntryMapper;
	
	
	private final List<String> widthList = Arrays.asList("107","108","117","118");
	private final List<String> buList = Arrays.asList("1354372609636470785","1354372897457999874","1354372428320903169","1354372542418554882","1381576142194450434","1409439090992369666");
	private final List<String> boppList = Arrays.asList("1356411274025914369","1356411519174594561","1356411875984035841","1357239475375607809","1376702451707002882","1354384851350228993","1354968337610076162","1425259315474161665");

	@Override
	@Transactional
	public void execute(JobExecutionContext context) throws JobExecutionException {
//		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DATE, -1);
//		Date d1 = null;
//		Date d2 = null;
//		try {
//			d1 = format.parse("2021-08-18");
//			d2 = format.parse("2021-08-19");
//		} catch (ParseException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
		//取出还没有计算工资的分切/切张单
		LambdaQueryWrapper<ZrkQzOrder> qzQuery = new LambdaQueryWrapper<>();
		qzQuery.eq(ZrkQzOrder::getMesOrderStatus, "4");
		qzQuery.eq(ZrkQzOrder::getDelFlag, "0");
		qzQuery.eq(ZrkQzOrder::getIsChedan, "0");
		qzQuery.eq(ZrkQzOrder::getIsSalary, "1");
		qzQuery.eq(ZrkQzOrder::getIsCalculated, "0");
		qzQuery.eq(ZrkQzOrder::getIsFinish, 1);
//		qzQuery.like(ZrkQzOrder::getOperatorUsers, "fc66541f299844a9a898777d9c1ae63b");
//		qzQuery.between(ZrkQzOrder::getCreateTime, d1, d2);
		List<ZrkQzOrder> list = this.qzOrderService.list(qzQuery);
		if(list == null || list.size() == 0) {
			return;
		}
		List<String> qzIds = Lists.newArrayList();//拆单前mes单号
		List<ZrkQzOrder> qzList = Lists.newArrayList();//切张mes单
		List<ZrkQzOrder> fqList = Lists.newArrayList();//分切mes单
		for(ZrkQzOrder qzOrder: list) {
			if(oConvertUtils.isNotEmpty(qzOrder.getParentId())) {
				qzIds.add(qzOrder.getParentId());
			}
			if(StringUtils.equals("1300701196116041729", qzOrder.getProcessId())
					|| StringUtils.equals("1300701144731623426", qzOrder.getProcessId())) {
				qzList.add(qzOrder);
			}
			if(StringUtils.equals("1300701063685087234", qzOrder.getProcessId())) {
				fqList.add(qzOrder);
			}
		}
		//切张计件工资。。。。。。。。。。
		if(qzList != null && qzList.size() > 0) {
			List<ZrkQzOrder> ptqzList = Lists.newArrayList();
			List<ZrkQzOrder> djqqzList = Lists.newArrayList();
			for(ZrkQzOrder qzOrder: qzList) {
				//判断是否是普通切张
				if(StringUtils.equals("1300701196116041729", qzOrder.getProcessId())) {
					ptqzList.add(qzOrder);
				}
				//判断是否是大机器切张
				if(StringUtils.equals("1300701144731623426", qzOrder.getProcessId())) {
					djqqzList.add(qzOrder);
				}
			}
			//计算普通切张当日工资。。。。。。。。。。
			if(ptqzList != null && ptqzList.size()>0) {
				Map<String, ZrkPiecerate> map = Maps.newHashMap();
				for(ZrkQzOrder qzOrder:ptqzList) {
					//先筛选出被拆单的数据不计算在内
					if(!qzIds.contains(qzOrder.getId())) {
						//操作员
						String[] userIds = qzOrder.getOperatorUsers().split(",");
						LambdaQueryWrapper<StkIoBill> query = new LambdaQueryWrapper<StkIoBill>();
						query.eq(StkIoBill::getSourceNo, qzOrder.getCode());
						query.eq(StkIoBill::getStockIoType, "1991");
						query.eq(StkIoBill::getIsClosed, 0);
						query.orderByDesc(StkIoBill::getCreateTime);
						List<StkIoBill> ioBillList = stkIoBillService.list(query);
						//生产完成可分多次入库，生成多条入库单，即1条mes单对多条入库单
						if(ioBillList != null && ioBillList.size() > 0) {
							List<String> ioBillIds = Lists.newArrayList();
							for(StkIoBill bill:ioBillList) {
								ioBillIds.add(bill.getId());
							}
							//查询所有入库明细
							List<StkIoBillEntry> entryList = ioBillEntryMapper.selectBatchByMainIdList(ioBillIds);
							List<String> materialIdList = Lists.newArrayList();
							if(entryList!=null && entryList.size()>0) {
								for(StkIoBillEntry entry:entryList) {
									materialIdList.add(entry.getMaterialId());
								}
								List<BasMaterial> materialList = basMaterialService.listByIds(materialIdList);
								List<String> codeList = Lists.newArrayList();
								if(materialList!=null && materialList.size()>0) {
									for(BasMaterial basMaterial:materialList) {
										codeList.add(basMaterial.getCode());
									}
									LambdaQueryWrapper<BasMaterialTemp> queryWrapper = new LambdaQueryWrapper<BasMaterialTemp>();
									queryWrapper.eq(BasMaterialTemp::getOrderId, qzOrder.getId());
									queryWrapper.in(BasMaterialTemp::getCode, codeList);
									List<BasMaterialTemp> tempList = basMaterialTempService.list(queryWrapper);
									if(tempList!=null && tempList.size()>0) {
										BigDecimal pageNum = BigDecimal.ZERO;//张数总和
										BigDecimal squareNum = BigDecimal.ZERO;//平方总和
										for(BasMaterialTemp basMaterialTemp:tempList) {
											try {
												ObjectValueUtils.getObjectValue(basMaterialTemp);
												BigDecimal page = basMaterialTemp.getPageNum()==null?BigDecimal.ZERO:basMaterialTemp.getPageNum();//张数
												pageNum = pageNum.add(page);
												BigDecimal square = BigDecimal.ZERO;//平方
												square = basMaterialTemp.getWidth()
																		.multiply(basMaterialTemp.getLength())
																		.divide(new BigDecimal("100"), 4, BigDecimal.ROUND_HALF_UP);
												squareNum = squareNum.add(square);
											} catch (Exception e) {
												
											}
										}
										BigDecimal setsNum = new BigDecimal(String.valueOf(tempList.size()));//总套数
										//工资计算
										BigDecimal salary = setsNum.multiply(new BigDecimal("2"))
																	.add(pageNum.multiply(new BigDecimal("0.0022")))
																	.add(squareNum.multiply(new BigDecimal("0.01")));
										for(String userId:userIds) {
											ZrkPiecerate piecerate = new ZrkPiecerate();
											piecerate.setZrkType(qzOrder.getProcessId());//计费类型（普通切张，大机器切张等）
											piecerate.setZrkTs(setsNum);//总套数
											piecerate.setZrkQzpf(squareNum);//张数总和
											piecerate.setZrkQzzs(pageNum);//平方总和
											piecerate.setZrkTotalmoney(salary);//该mes单薪资合计
											piecerate.setZrkUserid(userId);
											piecerate.setZrkJqbh(qzOrder.getMachineId());
											piecerate.setCreateTime(calendar.getTime());
											if(oConvertUtils.isEmpty(map.get(userId))) {
												map.put(userId, piecerate);
											}else {
												ZrkPiecerate rate = map.get(userId);
												rate.setZrkTs(rate.getZrkTs().add(piecerate.getZrkTs()));
												rate.setZrkQzpf(rate.getZrkQzpf().add(piecerate.getZrkQzpf()));
												rate.setZrkQzzs(rate.getZrkQzzs().add(piecerate.getZrkQzzs()));
												rate.setZrkTotalmoney(rate.getZrkTotalmoney().add(piecerate.getZrkTotalmoney()));
												map.put(userId, rate);
											}
										}
									}
								}
							}
						}
						qzOrder.setIsCalculated("1");//标记是否已计算过工资
					}
				}
				qzOrderService.updateBatchById(ptqzList);
				List<ZrkPiecerate> zrkPiecerateList = map.values().stream().collect(Collectors.toList());
				if(zrkPiecerateList!=null && zrkPiecerateList.size()>0) {
					piecerateService.saveBatch(zrkPiecerateList);
				}
			}
			//计算大机器切张当日工资。。。。。。。。。。
			if(djqqzList != null && djqqzList.size()>0) {
				Map<String, ZrkPiecerate> map = Maps.newHashMap();
				for(ZrkQzOrder qzOrder:djqqzList) {
					//先筛选出被拆单的数据不计算在内
					if(!qzIds.contains(qzOrder.getId())) {
						//操作员
						String[] userIds = qzOrder.getOperatorUsers().split(",");
						LambdaQueryWrapper<StkIoBill> query = new LambdaQueryWrapper<StkIoBill>();
						query.eq(StkIoBill::getSourceNo, qzOrder.getCode());
						query.eq(StkIoBill::getStockIoType, "1991");
						query.eq(StkIoBill::getIsClosed, 0);
						query.orderByDesc(StkIoBill::getCreateTime);
						List<StkIoBill> ioBillList = stkIoBillService.list(query);
						//生产完成可分多次入库，生成多条入库单，即1条mes单对多条入库单
						if(ioBillList != null && ioBillList.size() > 0) {
							List<String> ioBillIds = Lists.newArrayList();
							for(StkIoBill bill:ioBillList) {
								ioBillIds.add(bill.getId());
							}
							//查询所有入库明细
							List<StkIoBillEntry> entryList = ioBillEntryMapper.selectBatchByMainIdList(ioBillIds);
							List<String> materialIdList = Lists.newArrayList();
							if(entryList!=null && entryList.size()>0) {
								for(StkIoBillEntry entry:entryList) {
									materialIdList.add(entry.getMaterialId());
								}
								List<BasMaterial> materialList = basMaterialService.listByIds(materialIdList);
								List<String> codeList = Lists.newArrayList();
								if(materialList!=null && materialList.size()>0) {
									for(BasMaterial basMaterial:materialList) {
										codeList.add(basMaterial.getCode());
									}
								}
								LambdaQueryWrapper<BasMaterialTemp> queryWrapper = new LambdaQueryWrapper<BasMaterialTemp>();
								queryWrapper.eq(BasMaterialTemp::getOrderId, qzOrder.getId());
								queryWrapper.in(BasMaterialTemp::getCode, codeList);
								List<BasMaterialTemp> tempList = basMaterialTempService.list(queryWrapper);
								if(tempList!=null && tempList.size()>0) {
									BigDecimal pageNum = BigDecimal.ZERO;//张数总和
									BigDecimal squareNum = BigDecimal.ZERO;//平方总和
									for(BasMaterialTemp basMaterialTemp:tempList) {
										try {
											ObjectValueUtils.getObjectValue(basMaterialTemp);
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										BigDecimal page = basMaterialTemp.getPageNum()==null?BigDecimal.ZERO:basMaterialTemp.getPageNum();//张数
										pageNum = pageNum.add(page);
										BigDecimal square = BigDecimal.ZERO;//平方
										square = basMaterialTemp.getWidth()
																.multiply(basMaterialTemp.getLength())
																.divide(new BigDecimal("100"), 4, BigDecimal.ROUND_HALF_UP);
										squareNum = squareNum.add(square);
									}
//									BigDecimal setsNum = new BigDecimal(String.valueOf(tempList.size()));//总套数
									//工资计算
									BigDecimal salary = pageNum.multiply(new BigDecimal("0.002"))
																.add(squareNum.multiply(new BigDecimal("0.007")));
									for(String userId:userIds) {
										ZrkPiecerate piecerate = new ZrkPiecerate();
										piecerate.setZrkType(qzOrder.getProcessId());//计费类型（普通切张，大机器切张等）
										piecerate.setZrkQzpf(squareNum);//张数总和
										piecerate.setZrkQzzs(pageNum);//平方总和
										piecerate.setZrkTotalmoney(salary);//该mes单薪资合计
										piecerate.setZrkUserid(userId);
										piecerate.setCreateTime(calendar.getTime());
										if(oConvertUtils.isEmpty(map.get(userId))) {
											map.put(userId, piecerate);
										}else {
											ZrkPiecerate rate = map.get(userId);
											rate.setZrkTs(rate.getZrkTs().add(piecerate.getZrkTs()));
											rate.setZrkQzpf(rate.getZrkQzpf().add(piecerate.getZrkQzpf()));
											rate.setZrkQzzs(rate.getZrkQzzs().add(piecerate.getZrkQzzs()));
											rate.setZrkTotalmoney(rate.getZrkTotalmoney().add(piecerate.getZrkTotalmoney()));
											map.put(userId, rate);
										}
									}
								}
							}
						}
						qzOrder.setIsCalculated("1");//修改mes单是否已计算过工资为1
					}
				}
				qzOrderService.updateBatchById(djqqzList);
				List<ZrkPiecerate> zrkPiecerateList = map.values().stream().collect(Collectors.toList());
				if(zrkPiecerateList!=null && zrkPiecerateList.size()>0) {
					piecerateService.saveBatch(zrkPiecerateList);
				}
			}
		}
		
		//分切计件工资
		List<ZrkQzOrder> tfOrder = Lists.newArrayList();//13、14号机（1人干）
		List<ZrkQzOrder> fseOrder = Lists.newArrayList();//15、17、18号机（2人干，若一人干刀数*2）
		List<ZrkQzOrder> nOrder = Lists.newArrayList();//19号机（1人干）
		List<ZrkQzOrder> tsOrder = Lists.newArrayList();//12、16号机按刀数计算。（2人干、若1人干刀数*2）
		if(fqList != null && fqList.size() > 0) {
			for(ZrkQzOrder zrkQzOrder:fqList) {
				//判断机器是否是13、14号机
				if(StringUtils.equals("1300723646774124546", zrkQzOrder.getMachineId())
						|| StringUtils.equals("1300723710120697858", zrkQzOrder.getMachineId())) {
					tfOrder.add(zrkQzOrder);
				}
				//判断机器是否是15、17、18号机
				if(StringUtils.equals("1300723771378507778", zrkQzOrder.getMachineId())
						|| StringUtils.equals("1300723913594773506", zrkQzOrder.getMachineId())
						|| StringUtils.equals("1300723973963390978", zrkQzOrder.getMachineId())) {
					fseOrder.add(zrkQzOrder);
				}
				//判断机器是否是19号机
				if(StringUtils.equals("1300724045132341249", zrkQzOrder.getMachineId())) {
					nOrder.add(zrkQzOrder);
				}
				//判断机器是否是12、16号机
				if(StringUtils.equals("1300723562791575554", zrkQzOrder.getMachineId())
						|| StringUtils.equals("1300723843877052417", zrkQzOrder.getMachineId())) {
					tsOrder.add(zrkQzOrder);
				}
			}
			//计算13、14号机的分切计件工资
			if(tfOrder != null && tfOrder.size() > 0) {
				Map<String, ZrkPiecerate> map = Maps.newHashMap();
				BigDecimal length = new BigDecimal("500");//分切长度
				for(ZrkQzOrder zrkQzOrder:tfOrder) {
					if(!qzIds.contains(zrkQzOrder.getId())) {
						BigDecimal squareSum = BigDecimal.ZERO;//总平方数
						BigDecimal tdSum = BigDecimal.ZERO;//调刀数总和
						BigDecimal dsSum = BigDecimal.ZERO;//刀数总和
						ZrkPiecerate piecerate = map.get(zrkQzOrder.getOperatorUsers());
						if(oConvertUtils.isEmpty(piecerate)) {
							piecerate = new ZrkPiecerate();
						}
						piecerate.setZrkType(zrkQzOrder.getProcessId());//计费类型（普通切张，大机器切张，分切等）
						//13、14号机（1人干）
						piecerate.setZrkUserid(zrkQzOrder.getOperatorUsers());
						piecerate.setCreateTime(calendar.getTime());
						//查询分切参数
						Map<String, BigDecimal> paramMap = getParameters(zrkQzOrder.getId(), length);
						squareSum = paramMap.get("squareSum");
						tdSum = paramMap.get("tdSum");
						dsSum = paramMap.get("dsSum");
						if(oConvertUtils.isEmpty(piecerate.getZrkFqds())) {
							piecerate.setZrkFqds(dsSum);
						}else {
							piecerate.setZrkFqds(dsSum.add(piecerate.getZrkFqds()));
						}
						if(oConvertUtils.isEmpty(piecerate.getZrkFqtds())) {
							piecerate.setZrkFqtds(tdSum);
						}else {
							piecerate.setZrkFqtds(tdSum.add(piecerate.getZrkFqtds()));
						}
						if(oConvertUtils.isEmpty(piecerate.getZrkFqpf())) {
							piecerate.setZrkFqpf(squareSum);
						}else {
							piecerate.setZrkFqpf(squareSum.add(piecerate.getZrkFqpf()));
						}
						piecerate.setZrkJqbh(zrkQzOrder.getMachineId());
						//薪资合计=刀数（按500米计算/刀）*4.2元+调刀数*0.7元/刀
						BigDecimal money = dsSum.multiply(new BigDecimal("4.2")).add(tdSum.multiply(new BigDecimal("0.7")));
						if(oConvertUtils.isEmpty(piecerate.getZrkTotalmoney())) {
							piecerate.setZrkTotalmoney(money);
						}else {
							piecerate.setZrkTotalmoney(money.add(piecerate.getZrkTotalmoney()));
						}
						map.put(zrkQzOrder.getOperatorUsers(), piecerate);
						zrkQzOrder.setIsCalculated("1");//修改mes单是否已计算过工资为1
					}
				}
				qzOrderService.updateBatchById(tfOrder);
				List<ZrkPiecerate> zrkPiecerateList = map.values().stream().collect(Collectors.toList());
				if(zrkPiecerateList!=null && zrkPiecerateList.size()>0) {
					piecerateService.saveBatch(zrkPiecerateList);
				}
			}
		}
		//15、17、18号机（2人干，若一人干刀数*2）
		if(fseOrder != null && fseOrder.size() > 0) {
			Map<String, ZrkPiecerate> map = Maps.newHashMap();
			BigDecimal length = new BigDecimal("500");//分切长度
			for(ZrkQzOrder zrkQzOrder:fseOrder) {
				if(!qzIds.contains(zrkQzOrder.getId())) {
					BigDecimal squareSum = BigDecimal.ZERO;//总平方数
					BigDecimal tdSum = BigDecimal.ZERO;//调刀数总和
					BigDecimal dsSum = BigDecimal.ZERO;//刀数总和
					String[] userIds = zrkQzOrder.getOperatorUsers().split(",");
					//查询分切参数
					Map<String, BigDecimal> paramMap = getParameters(zrkQzOrder.getId(), length);
					squareSum = paramMap.get("squareSum");
					tdSum = paramMap.get("tdSum");
					dsSum = paramMap.get("dsSum");
					if(userIds!=null && userIds.length>0) {
						for(String userId:userIds) {
							ZrkPiecerate piecerate = map.get(userId);
							if(oConvertUtils.isEmpty(piecerate)) {
								piecerate = new ZrkPiecerate();
							}
							piecerate.setZrkType(zrkQzOrder.getProcessId());//计费类型（普通切张，大机器切张，分切等）
							//15、17、18号机（2人干，若一人干刀数*2）
							piecerate.setZrkUserid(userId);
							if(oConvertUtils.isEmpty(piecerate.getZrkFqds())) {
								piecerate.setZrkFqds(dsSum);
							}else {
								piecerate.setZrkFqds(dsSum.add(piecerate.getZrkFqds()));
							}
							if(oConvertUtils.isEmpty(piecerate.getZrkFqtds())) {
								piecerate.setZrkFqtds(tdSum);
							}else {
								piecerate.setZrkFqtds(tdSum.add(piecerate.getZrkFqtds()));
							}
							if(oConvertUtils.isEmpty(piecerate.getZrkFqpf())) {
								piecerate.setZrkFqpf(squareSum);
							}else {
								piecerate.setZrkFqpf(squareSum.add(piecerate.getZrkFqpf()));
							}
							piecerate.setZrkJqbh(zrkQzOrder.getMachineId());
							piecerate.setCreateTime(calendar.getTime());
							//15、17、18号机（2人干，若一人干刀数*2）
							BigDecimal money = BigDecimal.ZERO;
							if(userIds.length>1) {
								//薪资合计=刀数（按1000米计算/刀）*5.3元+调刀数*3元+平方数*0.0008元
								money = dsSum.multiply(new BigDecimal("5.3"))
														.add(tdSum.multiply(new BigDecimal("3")))
														.add(squareSum.multiply(new BigDecimal("0.0008")));
							}else {
								//薪资合计=2*刀数（按1000米计算/刀）*5.3元+调刀数*3元+平方数*0.0008元
								money = dsSum.multiply(new BigDecimal("5.3"))
											.multiply(new BigDecimal("2"))
											.add(tdSum.multiply(new BigDecimal("3")))
											.add(squareSum.multiply(new BigDecimal("0.0008")));
							}
							if(oConvertUtils.isEmpty(piecerate.getZrkTotalmoney())) {
								piecerate.setZrkTotalmoney(money);
							}else {
								piecerate.setZrkTotalmoney(money.add(piecerate.getZrkTotalmoney()));
							}
							map.put(userId, piecerate);
						}
					}
					zrkQzOrder.setIsCalculated("1");//修改mes单已计算过工资为（1）
				}
			}
			qzOrderService.updateBatchById(fseOrder);
			List<ZrkPiecerate> zrkPiecerateList = map.values().stream().collect(Collectors.toList());
			if(zrkPiecerateList!=null && zrkPiecerateList.size()>0) {
				piecerateService.saveBatch(zrkPiecerateList);
			}
		}
		
		//19号机（1人干）
		if(nOrder != null && nOrder.size() > 0) {
			Map<String, ZrkPiecerate> map = Maps.newHashMap();
			BigDecimal length = new BigDecimal("500");//分切长度
			for(ZrkQzOrder zrkQzOrder:nOrder) {
				if(!qzIds.contains(zrkQzOrder.getId())) {
					BigDecimal squareSum = BigDecimal.ZERO;//总平方数
					BigDecimal tdSum = BigDecimal.ZERO;//调刀数总和
					BigDecimal dsSum = BigDecimal.ZERO;//刀数总和
					//查询分切参数
					Map<String, BigDecimal> paramMap = getParameters(zrkQzOrder.getId(), length);
					squareSum = paramMap.get("squareSum");
					tdSum = paramMap.get("tdSum");
					dsSum = paramMap.get("dsSum");
					ZrkPiecerate piecerate = map.get(zrkQzOrder.getOperatorUsers());
					if(oConvertUtils.isEmpty(piecerate)) {
						piecerate = new ZrkPiecerate();
					}
					piecerate.setZrkType(zrkQzOrder.getProcessId());//计费类型（普通切张，大机器切张，分切等）
					//19号机（1人干）
					piecerate.setZrkUserid(zrkQzOrder.getOperatorUsers());
					if(oConvertUtils.isEmpty(piecerate.getZrkFqds())) {
						piecerate.setZrkFqds(dsSum);
					}else {
						piecerate.setZrkFqds(dsSum.add(piecerate.getZrkFqds()));
					}
					if(oConvertUtils.isEmpty(piecerate.getZrkFqtds())) {
						piecerate.setZrkFqtds(tdSum);
					}else {
						piecerate.setZrkFqtds(tdSum.add(piecerate.getZrkFqtds()));
					}
					if(oConvertUtils.isEmpty(piecerate.getZrkFqpf())) {
						piecerate.setZrkFqpf(squareSum);
					}else {
						piecerate.setZrkFqpf(squareSum.add(piecerate.getZrkFqpf()));
					}
					piecerate.setZrkJqbh(zrkQzOrder.getMachineId());
					piecerate.setCreateTime(calendar.getTime());
					//薪资合计=刀数（按1000米计算）*9元+平方数*0.0008元
					BigDecimal money = dsSum.multiply(new BigDecimal("9"))
											.add(squareSum.multiply(new BigDecimal("0.0008")));
					if(oConvertUtils.isEmpty(piecerate.getZrkTotalmoney())) {
						piecerate.setZrkTotalmoney(money);
					}else {
						piecerate.setZrkTotalmoney(money.add(piecerate.getZrkTotalmoney()));
					}
					map.put(zrkQzOrder.getOperatorUsers(), piecerate);
					zrkQzOrder.setIsCalculated("1");//修改mes单已计算过工资为（1）
				}
			}
			qzOrderService.updateBatchById(nOrder);
			List<ZrkPiecerate> zrkPiecerateList = map.values().stream().collect(Collectors.toList());
			if(zrkPiecerateList!=null && zrkPiecerateList.size()>0) {
				piecerateService.saveBatch(zrkPiecerateList);
			}
		}
		
		//12、16号机按刀数计算。（2人干、若1人干刀数*2）
		if(tsOrder != null && tsOrder.size() > 0) {
			LambdaQueryWrapper<BasMaterialCategory> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.like(BasMaterialCategory::getFullname, "/QA/")
						.or()
						.like(BasMaterialCategory::getFullname, "/TE/");
			List<BasMaterialCategory> categoryList = categoryService.list(queryWrapper);
			List<String> categoryIdList = Lists.newArrayList();
			if(categoryList!=null && categoryList.size()>0) {
				for(BasMaterialCategory category:categoryList) {
					categoryIdList.add(category.getId());
				}
			}
			Map<String, ZrkPiecerate> map = Maps.newHashMap();
			for(ZrkQzOrder zrkQzOrder:tsOrder) {
				if(!qzIds.contains(zrkQzOrder.getId())) {
					BigDecimal squareSum = BigDecimal.ZERO;//总平方数
					BigDecimal tdSum = BigDecimal.ZERO;//调刀数总和
					BigDecimal dsSum = BigDecimal.ZERO;//刀数总和
					//区分记录不同物料分类不同计算计件工资
					Map<String, BigDecimal> sumMap = Maps.newHashMap();
					//初始化sumMap
					sumMap.put("fjtDs", BigDecimal.ZERO);//记录分卷筒计算方式——>刀数
					sumMap.put("ds", BigDecimal.ZERO);//记录普通计算方式——>刀数
					sumMap.put("tds", BigDecimal.ZERO);//记录调刀数
					sumMap.put("boppDs", BigDecimal.ZERO);//记录BOPP物料刀数
					//查询分切参数
					List<ZrkMesFqParamVO> zrkMesFqParams=zrkMesFqParamService.selectParamBymesId(zrkQzOrder.getId());
					if(zrkMesFqParams !=null && zrkMesFqParams.size() > 0) {
						for(ZrkMesFqParamVO vo:zrkMesFqParams) {
							BigDecimal squares = BigDecimal.ZERO;//每个排刀方案分切总数量
							try {
								if(oConvertUtils.isNotEmpty(vo.getPartParam())) {
									String[] w = StringUtils.split(vo.getPartParam(), "=");
									if(w!=null&&w.length>0) {
										if(StringUtils.contains(vo.getPartParam(), "=")&&oConvertUtils.isNotEmpty(w[1])&&isNumber(w[1])) {
											squares = new BigDecimal(w[1])
													.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP)
													.multiply(new BigDecimal(vo.getHeight())).add(squares);
										}else {
											if(oConvertUtils.isNotEmpty(w[0])) {
												String[] wi = StringUtils.split(w[0], "+");
												if(wi!=null && wi.length>0) {
													for(String wid:wi) {
														String[] widt = StringUtils.split(wid, "*");
														if(widt!=null && widt.length>0) {
															if(isNumber(widt[0]) 
																	&& oConvertUtils.isNotEmpty(widt[0]) 
																	&& oConvertUtils.isNotEmpty(vo.getHeight())) {
																BigDecimal sq = new BigDecimal(widt[0])
																		.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP)
																		.multiply(new BigDecimal(vo.getHeight()));
																if(widt.length>1 && StringUtils.contains(wid, "*") && oConvertUtils.isNotEmpty(widt[1])) {
																	sq = sq.multiply(new BigDecimal(widt[1]));
																}
																squares = squares.add(sq);
															}else {
																System.err.println(widt[0]);
															}
														}
													}
												}
											}
										}
									}
								}
							}catch (Exception e) {
								// TODO: handle exception
								//防止填写生产参数时不按要求填写，出错影响其他计件工资
//								throw new JeecgBootException("计算分切计件工资中的平方错误");
							}
							if(oConvertUtils.isNotEmpty(vo.getQuantity())) {
								//平方数*分切刀数=每条生产参数的平方数，再累加
								squares = squares.multiply(new BigDecimal(String.valueOf(vo.getQuantity())));
								squareSum = squareSum.add(squares);
								dsSum = dsSum.add(new BigDecimal(String.valueOf(vo.getQuantity())));//计算分切刀数
							}
							//缠卷计算方式（尺寸包括107、117、108、118的任何材料），但无调刀数
							//刀数（不分米数）*4.5元+平方数*0.0008元
							if(widthList.contains(vo.getWidth())) {
								//刀数
								sumMap.put("ds", sumMap.get("ds").add(new BigDecimal(String.valueOf(vo.getQuantity()))));
							}else if(!widthList.contains(vo.getWidth()) && categoryIdList.contains(vo.getCategoryId()) || buList.contains(vo.getCategoryId())) {
								//记录分卷筒计算方式——>刀数
								sumMap.put("fjtDs", sumMap.get("fjtDs").add(new BigDecimal(String.valueOf(vo.getQuantity()))));
								//记录分卷筒计算方式——>调刀数
								sumMap.put("tds", sumMap.get("tds").add(BigDecimal.ONE));
							}else if(!widthList.contains(vo.getWidth()) && boppList.contains(vo.getCategoryId())){
								//记录BOPP材料——>刀数
								sumMap.put("boppDs", sumMap.get("boppDs").add(new BigDecimal(String.valueOf(vo.getQuantity()))));
								//记录BOPP材料——>调刀数
								sumMap.put("tds", sumMap.get("tds").add(BigDecimal.ONE));
							}else {
								sumMap.put("ds", sumMap.get("ds").add(new BigDecimal(String.valueOf(vo.getQuantity()))));
								sumMap.put("tds", sumMap.get("tds").add(BigDecimal.ONE));
							}
							tdSum = tdSum.add(new BigDecimal(String.valueOf(zrkMesFqParams.size())));//计算调刀数
						}
					}
					String[] userIds = zrkQzOrder.getOperatorUsers().split(",");
					if(userIds!=null && userIds.length>0) {
						for(String userId:userIds) {
							ZrkPiecerate piecerate = map.get(userId);
							if(oConvertUtils.isEmpty(piecerate)) {
								piecerate = new ZrkPiecerate();
							}
							piecerate.setZrkType(zrkQzOrder.getProcessId());//计费类型（普通切张，大机器切张，分切等）
							piecerate.setZrkUserid(userId);
							
							piecerate.setZrkFqds(piecerate.getZrkFqds().add(sumMap.get("fjtDs"))
																		.add(sumMap.get("ds"))
																		.add(sumMap.get("boppDs")));
							piecerate.setZrkFqtds(piecerate.getZrkFqtds().add(sumMap.get("tds")));
							piecerate.setZrkFqpf(squareSum.add(piecerate.getZrkFqpf()));
							piecerate.setZrkJqbh(zrkQzOrder.getMachineId());
							piecerate.setCreateTime(calendar.getTime());
							//12、16号机（2人干，若一人干刀数*2）
							BigDecimal money = BigDecimal.ZERO;
							if(userIds.length>1) {
								// 薪资合计=刀数（不分米数）*4.5元+调刀数*2.5元+平方数*0.0008元
								//+缠卷计算方式薪资合计=刀数（不分米数）*4.5元+平方数*0.0008元
								//+分卷筒薪资合计=刀数（不分米数）*6.5元+调刀数*2.5元+平方数*0.0008元
								//+BOPP薪资合计=刀数（不分米数）*5.5元+调刀数*2.5元+平方数*0.0008元
								//=总计件工资
								money = sumMap.get("ds").multiply(new BigDecimal("4.5"))
										.add(sumMap.get("fjtDs").multiply(new BigDecimal("6.5")))
										.add(sumMap.get("boppDs").multiply(new BigDecimal("5.5")))
										.add(sumMap.get("tds").multiply(new BigDecimal("2.5")))
										.add(squareSum.multiply(new BigDecimal("0.0008")));
							}else {
								// 薪资合计=2*刀数（不分米数）*4.5元+调刀数*2.5元+平方数*0.0008元
								//+缠卷计算方式薪资合计=2*刀数（不分米数）*4.5元+平方数*0.0008元
								//+分卷筒薪资合计=2*刀数（不分米数）*6.5元+调刀数*2.5元+平方数*0.0008元
								//+BOPP薪资合计=2*刀数（不分米数）*5.5元+调刀数*2.5元+平方数*0.0008元
								money = new BigDecimal("2").multiply(
										sumMap.get("ds").multiply(new BigDecimal("4.5"))
										.add(sumMap.get("fjtDs").multiply(new BigDecimal("6.5")))
										.add(sumMap.get("boppDs").multiply(new BigDecimal("5.5"))))
										.add(sumMap.get("tds").multiply(new BigDecimal("2.5")))
										.add(squareSum.multiply(new BigDecimal("0.0008")));
							}
							if(oConvertUtils.isEmpty(piecerate.getZrkTotalmoney())) {
								piecerate.setZrkTotalmoney(money);
							}else {
								piecerate.setZrkTotalmoney(money.add(piecerate.getZrkTotalmoney()));
							}
							map.put(userId, piecerate);
						}
					}
					zrkQzOrder.setIsCalculated("1");//修改mes单已计算过工资为（1）
				}
			}
			qzOrderService.updateBatchById(tsOrder);
			List<ZrkPiecerate> zrkPiecerateList = map.values().stream().collect(Collectors.toList());
			if(zrkPiecerateList!=null && zrkPiecerateList.size()>0) {
				piecerateService.saveBatch(zrkPiecerateList);
			}
		}
	}
	
	private Map<String, BigDecimal> getParameters(String id, BigDecimal length){
		Map<String, BigDecimal> map = Maps.newHashMap();
		BigDecimal squareSum = BigDecimal.ZERO;//总平方数
		BigDecimal tdSum = BigDecimal.ZERO;//调刀数总和
		BigDecimal lengthSum = BigDecimal.ZERO;//物料长度总和
		BigDecimal dsSum = BigDecimal.ZERO;//刀数总和
		List<ZrkMesFqParamVO> zrkMesFqParams=zrkMesFqParamService.selectParamBymesId(id);
		if(zrkMesFqParams !=null && zrkMesFqParams.size() > 0) {
			for(ZrkMesFqParamVO vo:zrkMesFqParams) {
				BigDecimal squares = BigDecimal.ZERO;//每个排刀方案分切总数量
				try {
					if(oConvertUtils.isNotEmpty(vo.getPartParam())) {
						String[] w = StringUtils.split(vo.getPartParam(), "=");
						if(w!=null&&w.length>0) {
							if(StringUtils.contains(vo.getPartParam(), "=")&&oConvertUtils.isNotEmpty(w[1])&&isNumber(w[1])) {
								squares = new BigDecimal(w[1])
										.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP)
										.multiply(new BigDecimal(vo.getHeight())).add(squares);
							}else {
								if(oConvertUtils.isNotEmpty(w[0])) {
									String[] wi = StringUtils.split(w[0], "+");
									if(wi!=null && wi.length>0) {
										for(String wid:wi) {
											String[] widt = StringUtils.split(wid, "*");
											if(widt!=null && widt.length>0) {
												if(isNumber(widt[0])
														&& oConvertUtils.isNotEmpty(widt[0]) 
														&& oConvertUtils.isNotEmpty(vo.getHeight())) {
													BigDecimal sq = new BigDecimal(widt[0])
															.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP)
															.multiply(new BigDecimal(vo.getHeight()));
													if(widt.length>1 && StringUtils.contains(wid, "*") && oConvertUtils.isNotEmpty(widt[1])) {
														sq = sq.multiply(new BigDecimal(widt[1]));
													}
													squares = squares.add(sq);
												}else {
													System.err.println(widt[0]);
												}
											}
										}
									}
								}
							}
						}
					}
				}catch (Exception e) {
					// TODO: handle exception
					//防止填写生产参数时不按要求填写，出错影响其他计件工资
//					throw new JeecgBootException("计算分切计件工资中的平方错误",e);
				}
//				if(oConvertUtils.isNotEmpty(vo.getQuantity())) {
//					//平方数*分切刀数=每条生产参数的平方数，再累加
//					squareSum = squareSum.add(squares.multiply(new BigDecimal(String.valueOf(vo.getQuantity()))));
//					dsSum = dsSum.add(new BigDecimal(String.valueOf(vo.getQuantity())));//计算分切刀数
//				}
			}
			tdSum = tdSum.add(new BigDecimal(String.valueOf(zrkMesFqParams.size())));//计算调刀数
		}
		map.put("tdSum", tdSum);
		LambdaQueryWrapper<StkIoBill> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(StkIoBill::getSourceId, id);
		queryWrapper.eq(StkIoBill::getStockIoType, "1993");
		List<StkIoBill> billList = stkIoBillService.list(queryWrapper);
		List<String> billIdList = Lists.newArrayList();
		if(billList!=null && billList.size()>0) {
			for(StkIoBill ioBill:billList) {
				billIdList.add(ioBill.getId());
			}
			List<StkIoBillEntry> entryList = ioBillEntryMapper.selectBatchByMainIdList(billIdList);
			List<String> materialIdList = Lists.newArrayList();
			if(entryList!=null && entryList.size()>0) {
				for(StkIoBillEntry entry:entryList) {
					materialIdList.add(entry.getMaterialId());
				}
				List<BasMaterial> materialList = basMaterialService.listByIds(materialIdList);
				if(materialList!=null && materialList.size()>0) {
					List<String> pidList = Lists.newArrayList();
					for(BasMaterial material:materialList) {
						if(StringUtils.isNotBlank(material.getPid())) {
							String[] pids = StringUtils.split(material.getPid(), ",");
							for(String pid:pids) {
								if(!CollUtil.contains(pidList, pid)) {
									pidList.add(pid);
								}
							}
						}
					}
					if(pidList!=null && pidList.size()>0) {
						List<BasMaterial> pidMaterialList = basMaterialService.listByIds(pidList);
						if(pidMaterialList!=null && pidMaterialList.size()>0) {
							for(BasMaterial material:pidMaterialList) {
								if(material.getLength()!=null) {
									lengthSum = lengthSum.add(material.getLength());
									if(material.getWidth()!=null) {
										squareSum = squareSum.add(material.getLength()
													.multiply(material.getWidth())
													.divide(new BigDecimal("100"), 4, BigDecimal.ROUND_HALF_UP));
									}
								}
							}
						}
					}
				}
			}
		}
		map.put("squareSum", squareSum);
		dsSum = lengthSum.divide(length, 0, BigDecimal.ROUND_DOWN);
		map.put("dsSum", dsSum);
		return map;
	}
	
	private boolean isNumber(String number) {
		int index = number.indexOf(".");
		if (index < 0) {
			return StringUtils.isNumeric(number);
		} else {
			String num1 = number.substring(0, index);
			String num2 = number.substring(index + 1);

			return StringUtils.isNumeric(num1) && StringUtils.isNumeric(num2);
		}
	}
}
